package com.kevin.service.config;

import cn.dev33.satoken.exception.InvalidContextException;
import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.kevin.common.constants.Constants;
import com.kevin.service.entity.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * SaPermissionHolder
 *
 * @author wh
 * @date 2022/5/10 14:23
 */
@Configuration
@Slf4j
public class StpUserHolder implements StpInterface {


    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        return getUserFromSession().getPermissionList();
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        return getUserFromSession().getRoleList();
    }

    public static String getName() {
        SysUser user = getUserFromSession();
        return user == null ? StrUtil.EMPTY : user.getRealName();
    }

    public static Long getId() {
        return getUserFromSession().getId();
    }

    /**
     * 向当前用户的Session中设置用户信息
     *
     * @param user 用户信息
     */
    public static void setUserToSession(SysUser user) {
        StpUtil.getSession().set(Constants.SA_SESSION_KEY_USER, user);
    }

    public static SysUser getUserFromSession() {
        try {
            return StpUtil.getSession().getModel(Constants.SA_SESSION_KEY_USER, SysUser.class);
        } catch (InvalidContextException e) {
            // 系统启动的时候无法获取到
            log.warn("系统启动时,无法获取到stp context");
            SysUser sysUser = new SysUser();
            sysUser.setId(0L);
            sysUser.setUsername("system");
            return sysUser;
        }
    }

}
